package sindconsole.auth.webapp;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import sindconsole.auth.bean.Account;
import sindconsole.auth.bean.User;
import sindconsole.auth.bean.UserPrincipal;
import sindconsole.auth.service.AuthService;

@Component
public class AuthRealm extends AuthorizingRealm {

    /* @Lazy must be presented, unless want more 'is not eligible for getting processed by all BeanPostProcessors'  */
    @Autowired
    @Lazy
    AuthService authService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        UserPrincipal principle = (UserPrincipal)getAvailablePrincipal(principals);
        User user = principle.getUser();
        if(user == null) throw new UnknownAccountException();

        SimpleAuthorizationInfo result = new SimpleAuthorizationInfo();
        result.setRoles(authService.findUserRoleKeys(user.getId()));
        result.setStringPermissions(authService.findAllUserPermissionKeys(user.getId()));

        return result;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        Account account = authService.findAccount(username);
        if(account == null) throw new UnknownAccountException();
        String password = new String((char[])token.getCredentials());
        User user = authService.authc(account, password);
        if(user == null) throw new IncorrectCredentialsException();
        if(user.getStatus() < 0) throw new DisabledAccountException();
        account.setPassword(null);
        UserPrincipal principle = new UserPrincipal(account, user);
        return new SimpleAuthenticationInfo(principle, password, getName());
    }

}
